<template>
	<div>
		<CustomDialog
			:title="state.dialog.title"
			v-model:visible="state.dialog.isShowDialog"
			dialogWidth="900px"
			@close="handleGoodsDataClose"
			:dialogFooterBtn="true"
		>
			<div class="">
				<el-alert title="注意：改价订单不会影响原分佣金额" type="warning" />
				<div class="mt10">
					<el-form label-width="150" ref="goodsUpdatePriceDialogFormRef" :model="state.ruleForm">
						<el-form-item label="当前订单总金额">
							<el-input disabled v-model="state.ruleForm.price" disable>
								<template #append> 元</template>
							</el-input>
						</el-form-item>

						<el-form-item label="修改价格" prop="newPrice" :rules="{ required: true, message: '修改后的价格不能为空', trigger: 'blue' }">
							<el-input v-model="state.ruleForm.newPrice" type="number" min="0.1" step="0.1">
								<template #append> 元</template>
							</el-input>
						</el-form-item>

						<el-form-item label="改价原因" prop="reason" :rules="{ required: true, message: '改价原因不能为空', trigger: 'blue' }">
							<el-input v-model="state.ruleForm.reason" />
						</el-form-item>
					</el-form>
				</div>
			</div>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleGoodsDataClose" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(goodsUpdatePriceDialogFormRef)" size="default">确定</el-button>
				</span>
			</template>
		</CustomDialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { orderApi } from '/@/api/shop/order';
import msg from '/@/utils/messageUtils';
import type { FormInstance } from 'element-plus';

const emits = defineEmits(['refreshOrderStatus']);

const goodsUpdatePriceDialogFormRef = ref();
const state = reactive({
	dialog: {
		isShowDialog: false,
		type: '',
		title: '商品改价',
		submitTxt: '',
	},
	ruleForm: {
		id: '',
		price: '',
		newPrice: '',
		reason: '',
	},
});
const openInit = async (id: string) => {
	state.dialog.isShowDialog = true;
	try {
		const { data } = await orderApi().viewUpdatePrice(id);
		console.log('data: ', data);
		state.ruleForm.id = id;
		state.ruleForm.price = data.originalPrice;
		state.ruleForm.newPrice = data.targetPrice;
		state.ruleForm.reason = data.reason;
	} catch (e) {
		msg().error('查询商品信息失败，请重试.');
	}
};

const handleGoodsDataClose = () => {
	state.dialog.isShowDialog = false;
};

const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid, errors) => {
		if (valid) {
			console.log('hello world');
			try {
				const { data } = await orderApi().updatePrice({
					targetPrice: state.ruleForm.newPrice,
					reason: state.ruleForm.reason,
					id: state.ruleForm.id,
				});
				msg().success('改价成功..');
				handleGoodsDataClose();
				emits('refreshOrderStatus');
			} catch (e) {
				msg().error('改价失败，请稍后重试...');
			}
		}
	});
};

defineExpose({
	openInit,
});
</script>

<style scoped lang="scss"></style>
